package me.ak.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import me.ak.file.Saveable;
import me.ak.utils.CManip;

import org.jnbt.CompoundTag;
import org.jnbt.IntTag;
import org.jnbt.ListTag;
import org.jnbt.Tag;
import org.lwjgl.util.Point;


/**
*The class that holds all information on a specific bar.
**/
public class BarModel extends Model implements Saveable{
	
	private List<ChordModel> chords = new ArrayList<ChordModel>();
	/**
	 * The score.
	 */
	private ScoreModel parent;
	
	/**
	 * The unique id of this bar.
	 */
	private int UID;
	
	/**
	 * The time signature of the bar.
	 */
	private TimeSignature tSig;
	private KeySignature kSig;
	
	
	public BarModel(int id, ScoreModel parent) {
		this.UID = id;
		this.parent = parent;
		kSig = new KeySignature(0, false);
		tSig = new TimeSignature(16, 4);
	}
	
	public ScoreModel getParent() {
		return parent;
	}
	
	public Point getLocation() {
		return parent.getBarLocation(this);
	}
	
	public int getUID() {
		return UID;
	}
	
	public TimeSignature getTimeSignature() {
		return tSig;
	}
	
	public KeySignature getKeySignature() {
		return kSig;
	}
	
	public int countNotes() {
		return chords.size();
	}
	
	public int countMeasureBeats() {
		return tSig.getBeatsPerMeasure();
	}
	
	public int getAllowedChordLength() {
		return tSig.getBeatValue() * tSig.getBeatsPerMeasure();
	}
	
	public boolean addChord(ChordModel cm) {
		int cl = cm.getLength();
		int tl = 0;
		for (ChordModel c : chords) {
			tl += c.getLength();
		}
		if (tl + cl > getAllowedChordLength()) {
			return false;
		}
		
		cm.setIndex(chords.size());
		chords.add(cm);
		return true;
	}
	
	
	
	
	private static int idcount = -1;
	public static int createUID() {
		idcount ++;
		return idcount;
	}

	@Override
	public CompoundTag saveNBT() {
		HashMap<String, Tag> barRoot = CManip.initMap();
		HashMap<String, Tag> chordRoot = CManip.initMap(); //stores all chords
		for (int i = 0; i < chords.size(); i++) {
			chordRoot.put("Chord"+i, chords.get(i).saveNBT());
			System.out.println("Adding chord");
		}
		ListTag chordRootTag = new ListTag("Chords", CompoundTag.class, new ArrayList<Tag>(chordRoot.values()));
		barRoot.put("Chords", chordRootTag);
		barRoot.put("UID", new IntTag("UID", this.UID));
		barRoot.put("BARX", new IntTag("BarX", this.parent.getBarLocation(this).getX()));
		barRoot.put("BARY", new IntTag("BarY", this.parent.getBarLocation(this).getY()));
		
		CompoundTag toReturn = new CompoundTag("Bar", barRoot);
		return toReturn;
	}

	@Override
	public void readNBT(CompoundTag t) {
		
	}
}
